package com.bhs.sansonglogistics.ui.home;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.ArrayMap;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.bean.AdvertisingBean;
import com.bhs.sansonglogistics.bean.MenuBean;
import com.bhs.sansonglogistics.bean.UserDTO;
import com.bhs.sansonglogistics.bean.UserInfoBean;
import com.bhs.sansonglogistics.bean.event.CompanyInfo;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.adapter.MenuAdapter;
import com.bhs.sansonglogistics.ui.enterprise.CompanyDetailsActivity;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseCertificationActivity;
import com.bhs.sansonglogistics.ui.message.VisitorLogActivity;
import com.bhs.sansonglogistics.ui.mine.BehaviorActivity;
import com.bhs.sansonglogistics.ui.mine.CashTransitActivity;
import com.bhs.sansonglogistics.ui.mine.CommonProblemActivity;
import com.bhs.sansonglogistics.ui.mine.CustomerServiceActivity;
import com.bhs.sansonglogistics.ui.mine.FeedbackActivity;
import com.bhs.sansonglogistics.ui.mine.InvoiceManagementActivity;
import com.bhs.sansonglogistics.ui.mine.MyBillActivity;
import com.bhs.sansonglogistics.ui.mine.MyRevenueActivity;
import com.bhs.sansonglogistics.ui.mine.PersonalInformationActivity;
import com.bhs.sansonglogistics.ui.mine.SettingActivity;
import com.bhs.sansonglogistics.ui.mine.StaffManagementActivity;
import com.bhs.sansonglogistics.ui.order.ScanCodeDeliveryActivity;
import com.bhs.sansonglogistics.ui.other.TestActivity;
import com.bhs.sansonglogistics.ui.wallet.BalanceActivity;
import com.bhs.sansonglogistics.ui.wallet.BankCardActivity;
import com.bhs.sansonglogistics.ui.wallet.MyRedEnvelopeActivity;
import com.bhs.sansonglogistics.utils.FastCilckOneUtil;
import com.bhs.sansonglogistics.utils.LogUtils;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.banner.AutoScrollViewPager;
import com.bhs.sansonglogistics.view.banner.BannerIndicator;
import com.bhs.sansonglogistics.view.banner.ViewPagerAdapter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 我的
 */
public class MineFragment extends BaseFragment implements View.OnClickListener, NetCallBack {

    private ImageView mIvScanCode;
    private ImageView mIvSet;
    private ImageView mIvHead;
    private TextView mTvTitle;
    private ImageView mIvAuthority;
    private TextView mTvBehavior;
    private TextView mTvVisitor;
    private TextView mTvCollect;
    private TextView mTvScore;
    private RelativeLayout mRlCarousel;
    private AutoScrollViewPager mVpCarousel;
    private BannerIndicator mIndicator;
    private TextView mTvCashTransit;
    private TextView mTvRemainingSum;
    private TextView mTvEnvelope;
    private TextView mTvBankCard;
    private RecyclerView mRvFunction;
    private RecyclerView mRvFeedback;
    private TextView mTvNickName;
    private TextView mTvPhone;
    private UserInfoBean infoBean;

    private final String serviceTel = "4008899050";
    private String url;

    public static MineFragment newInstance() {
        return new MineFragment();
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_mine;
    }

    @Override
    public void initView(View root) {

    }


    @Override
    public void prestrain() {
        super.prestrain();
        View root = view;
        mIvScanCode = root.findViewById(R.id.iv_scan_code);
        mIvScanCode.setOnClickListener(this);
        mIvSet = root.findViewById(R.id.iv_set);
        mIvHead = root.findViewById(R.id.iv_head);
        mTvTitle = root.findViewById(R.id.tv_title);
        mIvAuthority = root.findViewById(R.id.iv_authority);
        mTvBehavior = root.findViewById(R.id.tv_behavior);
        mTvVisitor = root.findViewById(R.id.tv_visitor);
        mTvCollect = root.findViewById(R.id.tv_collect);
        mTvScore = root.findViewById(R.id.tv_score);
        mRlCarousel = root.findViewById(R.id.rl_carousel);
        mVpCarousel = root.findViewById(R.id.vp_carousel);
        mIndicator = root.findViewById(R.id.indicator);
        mTvCashTransit = root.findViewById(R.id.tv_cash_transit);
        mTvRemainingSum = root.findViewById(R.id.tv_remaining_sum);
        mTvEnvelope = root.findViewById(R.id.tv_envelope);
        mTvBankCard = root.findViewById(R.id.tv_bank_card);
        mRvFunction = root.findViewById(R.id.rv_function);
        mRvFeedback = root.findViewById(R.id.rv_feedback);
        mIvSet.setOnClickListener(this);
        root.findViewById(R.id.cl_personal_information).setOnClickListener(this);
        root.findViewById(R.id.ll_bank_card).setOnClickListener(this);
        root.findViewById(R.id.ll_balance).setOnClickListener(this);
        root.findViewById(R.id.ll_cash_transit).setOnClickListener(this);
        root.findViewById(R.id.ll_envelope).setOnClickListener(this);
        root.findViewById(R.id.ll_behavior).setOnClickListener(this);
        root.findViewById(R.id.ll_visitor).setOnClickListener(this);
        root.findViewById(R.id.ll_collect).setOnClickListener(this);
        root.findViewById(R.id.ll_score).setOnClickListener(this);
        mTvNickName = root.findViewById(R.id.tv_nick_name);
        mTvPhone = root.findViewById(R.id.tv_phone);
        EventBus.getDefault().register(this);

        mRlCarousel.post(new Runnable() {
            @Override
            public void run() {
                LogUtils.d(mRlCarousel.getWidth()+"PPP"+mRlCarousel.getHeight());
            }
        });
    }

    @Override
    public void onResumes() {
        super.onResumes();
        networkRequest(netApi.get_user_info(), this);
        if (mVpCarousel != null) {
            mVpCarousel.startAutoPlay();
        }
    }


    @Override
    public void initData() {
        List<MenuBean> menuBeanList = new ArrayList<>();
        menuBeanList.add(new MenuBean("我的营收", R.mipmap.ic_revenue));
        menuBeanList.add(new MenuBean("我的账单", R.mipmap.ic_bill));
       // menuBeanList.add(new MenuBean("发票管理", R.mipmap.ic_invoice));
        menuBeanList.add(new MenuBean("企业认证", R.mipmap.ic_staff));

        MenuAdapter menuAdapter = new MenuAdapter(R.layout.item_menu2, menuBeanList);
        mRvFunction.setAdapter(menuAdapter);
        mRvFunction.setLayoutManager(new GridLayoutManager(activity, 4));

        List<MenuBean> menuBeanList2 = new ArrayList<>();
        menuBeanList2.add(new MenuBean("常见问题", R.mipmap.ic_fqa));
        menuBeanList2.add(new MenuBean("联系客服", R.mipmap.ic_service));
        menuBeanList2.add(new MenuBean("意见反馈", R.mipmap.ic_feedback));
        //menuBeanList.add(new MenuBean("银行卡", R.mipmap.ic_staff));

        MenuAdapter menuAdapter2 = new MenuAdapter(R.layout.item_menu2, menuBeanList2);
        mRvFeedback.setAdapter(menuAdapter2);
        mRvFeedback.setLayoutManager(new GridLayoutManager(activity, 4));

        menuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (FastCilckOneUtil.isFastClick()) {
                    return;
                }
                if (menuBeanList.get(position).getMenuName().equals("我的账单")) {
                    startActivity(new Intent(getActivity(), MyBillActivity.class));
                } else if (menuBeanList.get(position).getMenuName().equals("我的营收")) {
                    startActivity(new Intent(getActivity(), MyRevenueActivity.class));
                } else if (menuBeanList.get(position).getMenuName().equals("发票管理")) {
                    startActivity(new Intent(getActivity(), InvoiceManagementActivity.class));
                } else if (menuBeanList.get(position).getMenuName().equals("员工管理")) {
                    startActivity(new Intent(getActivity(), StaffManagementActivity.class));
                }else if (menuBeanList.get(position).getMenuName().equals("企业认证")) {
                    startActivity(new Intent(getContext(), EnterpriseCertificationActivity.class)
                            .putExtra("type", 1));
                }
            }
        });

        menuAdapter2.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (FastCilckOneUtil.isFastClick()) {
                    return;
                }
                if (menuBeanList2.get(position).getMenuName().equals("常见问题")) {
                    startActivity(new Intent(getActivity(), CommonProblemActivity.class));
                } else if (menuBeanList2.get(position).getMenuName().equals("联系客服")) {
                    // startActivity(new Intent(getActivity(), CustomerServiceActivity.class));
                    MyUtils.callPhone(getContext(), serviceTel);
                } else if (menuBeanList2.get(position).getMenuName().equals("意见反馈")) {
                    startActivity(new Intent(getActivity(), FeedbackActivity.class));
                }
            }
        });
        Map<String, String> map = new ArrayMap<>();
        map.put("platform", "logistics");
        map.put("city", "1");
        map.put("ad_sign", "AppLogisticsPersonal");
        networkRequest(netApi.get_ad_list(map), this, 9527);

    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (FastCilckOneUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_set:
                startActivity(new Intent(getActivity(), SettingActivity.class));
                break;
            case R.id.cl_personal_information:
                startActivity(new Intent(getActivity(), PersonalInformationActivity.class));
                break;
            case R.id.ll_bank_card:
                startActivity(new Intent(getActivity(), BankCardActivity.class));
                break;
            case R.id.ll_balance:
                startActivity(new Intent(getActivity(), BalanceActivity.class)
                        .putExtra("balance", mTvRemainingSum.getText().toString()));
                break;
            case R.id.iv_scan_code:
                String invite_code = SharedPreferencesUtils.getString(activity, "invite_code");
                if (SharedPreferencesUtils.getString(activity, "urlType").equals("1")) {
                    url = "https://saasdemo.sansongkeji.com/adminsite/#/agreement/register?code=" + invite_code;
                } else {
                    url = "https://test.sansongkeji.com/adminsite/#/agreement/register?code=" + invite_code;
                }
                startActivity(new Intent(getActivity(), ScanCodeDeliveryActivity.class)
                        .putExtra("type", 2)
                        .putExtra("url", url));
                break;
            case R.id.ll_cash_transit:
                startActivity(new Intent(getActivity(), CashTransitActivity.class)
                        .putExtra("unliquidated", mTvCashTransit.getText().toString()));
                break;
            case R.id.ll_envelope:
                startActivity(new Intent(getActivity(), MyRedEnvelopeActivity.class));
                break;
            case R.id.ll_behavior:
                startActivity(new Intent(getActivity(), BehaviorActivity.class)
                        .putExtra("Behavior",mTvBehavior.getText().toString()));
                break;
            case R.id.ll_visitor:
                startActivity(new Intent(getActivity(), VisitorLogActivity.class));
                break;
            case R.id.ll_score:
                startActivity(new Intent(getActivity(), CompanyDetailsActivity.class).
                        putExtra("item", 2));
                break;
        }
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if (requestCode == 0) {
            infoBean = new Gson().fromJson(json, UserInfoBean.class);
            setData(infoBean);
        } else if (requestCode == 9527) {
            AdvertisingBean infoBean = new Gson().fromJson(json, AdvertisingBean.class);
            if (infoBean.isStatus() && !MyUtils.isEmpty(infoBean.getData().getList())) {
                ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(infoBean.getData().getList(), getActivity(), 1,true);
                mVpCarousel.setAdapter(pagerAdapter);
                mIndicator.setUpWidthViewPager(mVpCarousel, infoBean.getData().getList().size());
            }
        }
    }

    private void setData(UserInfoBean infoBean) {
        if (infoBean.isStatus()) {
            UserDTO userDTO = infoBean.getData().getUser_info();
            mTvNickName.setText(userDTO.getNickname());
            mTvPhone.setText(userDTO.getMobile());
            SharedPreferencesUtils.saveString(getContext(), "face", userDTO.getHeaderpic());
            SharedPreferencesUtils.saveString(getContext(), "nickname", userDTO.getNickname());
            SharedPreferencesUtils.saveString(getContext(), "realName", userDTO.getTruename());
            SharedPreferencesUtils.saveBoolean(getContext(), "is_approve", userDTO.getIs_approve() == 1);
            SharedPreferencesUtils.saveString(getContext(), "circle_pic", userDTO.getCircle_pic());
            Glide.with(getContext()).load(userDTO.getHeaderpic()).into(mIvHead);
            CompanyInfo companyInfo = infoBean.getData().getLogistics_info();
            mTvRemainingSum.setText(companyInfo.getMoney01());
            int comment_num = Integer.parseInt(infoBean.getData().getLogistics_info().getComment_num())+1;
            mTvScore.setText(MyUtils.format2(Double.parseDouble(companyInfo.getGrade_score()) / comment_num));
            mTvBehavior.setText(MyUtils.behavior(companyInfo.getMoney03()));
            mTvCollect.setText(companyInfo.getCollect_count());
            mTvVisitor.setText(companyInfo.getVisitor_count());
            mTvEnvelope.setText(companyInfo.getMoney02());
            mTvBankCard.setText(infoBean.getData().getBank_count());
            mTvCashTransit.setText(infoBean.getData().getOnway_money());
            if (companyInfo.getIs_company_approve() == 1) {
                mIvAuthority.setVisibility(View.VISIBLE);
            } else {
                mIvAuthority.setVisibility(View.GONE);
            }
        } else {
            ToastUtil.show(infoBean.getMsg());
        }
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onEvent(UserInfoBean event) {
        setData(event);
    }


    @Override
    public void onStop() {
        super.onStop();
        if (mVpCarousel != null) {
            mVpCarousel.stopAutoPlay();
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}